package com.mytijian.task.zookeeper.listener.manager;

import com.mytijian.task.zookeeper.LeaderService;
import com.mytijian.task.zookeeper.listener.AbstractDataChangeListener;
import com.mytijian.task.util.IpAddressUtil;
import com.mytijian.task.zookeeper.ZookeeperRegistryCenter;
import com.mytijian.task.zookeeper.path.ServerPath;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;

import java.util.Objects;

public class LeaderListenerManager extends AbstractListenerManager {
    public LeaderListenerManager(ZookeeperRegistryCenter zookeeperRegistryCenter, LeaderService leaderService) {
        super(zookeeperRegistryCenter, leaderService);
    }
    @Override
    public void start() {
        addListener(ServerPath.instance, new LeaderServerCrashListener());
    }
    class LeaderServerCrashListener extends AbstractDataChangeListener {

        @Override
        protected void dataChanged(String path, TreeCacheEvent.Type eventType, String data) {
            if (eventType != TreeCacheEvent.Type.NODE_REMOVED) {
                return;
            }
            if (leaderService.hasLeader()) {
                return;
            }
            String ip = ServerPath.getIpFromInstanceValue(data);
            if (ip == null) {
                leaderService.executeInLeader();
                return;
            }
            // 让原来的主server重新抢占
            if (!Objects.equals(ip, IpAddressUtil.getLocalHost())) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            leaderService.executeInLeader();

        }
    }
}
